/*
 * Copyright 2009 Al Phillips.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import xsd4gorm.Xsd4Gorminator
import xsd4gorm.model.Domain
import xsd4gorm.gen.ClassSourceGenerator

def cli = new CliBuilder(usage: 'groovy xsd4gorm -d "dir" -p "package" XSDFile')
cli.d(longOpt: 'directory', 'optional target directory', args: 1)
cli.p(longOpt: 'package', 'optional package for generated classes', args: 1)

def opt = cli.parse(args)

if(!opt || opt.arguments().size() != 1){
    cli.usage()
} else {
    if(opt.p){
        // TODO: packages
    }
    def file = new File(opt.arguments()[0])
    Xsd4Gorminator gorminator = new Xsd4Gorminator(file)

    if(gorminator.isValidXSD()){
        Domain domain = gorminator.generate()
        File dir = null
        if(opt.d){
            dir = new File(opt.d) //"/home/alclaud/xsd_test1/"
            dir.mkdir()
        }
        domain.classes.each {domainClass ->
            File f
            def className = domainClass.name + ".groovy"
            if (dir){
                f = new File(dir, className)
            } else {
                f = new File(className)
            }
            println "generating ${className} to ${f.absolutePath}"
            f.write(new ClassSourceGenerator(domainClass).generate()) 
        }
        println "${domain.classes.size()} classes generated."
    } else {
        println "Your file is not a valid XML Schema Document"       
    }
}



